import type { GetRef, InputRef, TableProps } from 'antd';
import { Button, Form, Input, Modal, Popconfirm, Table, Row, Col } from 'antd';
import React, { useContext, useEffect, useRef, useState, useImperativeHandle } from 'react';
import notify from 'devextreme/ui/notify';
import {postCPASToolsAipsData} from '@/services/cpasRequest';
import "./_style.less"

type FormInstance<T> = GetRef<typeof Form<T>>;

const EditableContext = React.createContext<FormInstance<any> | null>(null);

interface Item {
  key: string;
  name: string;
  age: string;
  address: string;
}

interface EditableRowProps {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
}

const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<InputRef>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current?.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();

      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[{ required: true, message: `${title} is required.` }]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingInlineEnd: 24 }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

interface DataType {
  key: React.Key;
  name: string;
}

type ColumnTypes = Exclude<TableProps<DataType>['columns'], undefined>;

const SetStandardType = React.forwardRef((props: {
  dbname: string,
  dataList: [],
  okCallback?: (data: any) => void; //成功回调,
  cancelCallback?: () => void; //失败回调
}, ref: any) => {
  const {dbname, okCallback, cancelCallback, dataList} = props;
  const [dataSource, setDataSource] = useState<DataType[]>([
    {
      key: '0',
      name: '采购',
    },
    {
      key: '1',
      name: '销售',
    },
    {
      key: '2',
      name: '生产',
    },
    {
      key: '3',
      name: '委外加工',
    },
  ]);

  const [count, setCount] = useState(2);
  const [inputVal, setInputVal] = useState("");
  const [confirmOpen, setConfirmOpen] = useState(false);

  useImperativeHandle(ref, () => ({
    show: async () => {
      setConfirmOpen(true);
    },
    close: () => {
      setConfirmOpen(false);
    },
  }));
  useEffect(() => {
    setDataSource(dataList);
  },[dbname, dataList]);
  const handleDelete = (key: React.Key) => {
    console.log('newData---', key);
    const newData = dataSource.filter((item) => item.key !== key);
    setDataSource([...newData]);
  };

  const defaultColumns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[] = [
    {
      title: '类型名称',
      dataIndex: 'name',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: '100px',
      render: (_, record) =>
        dataSource.length >= 1 ? (
          <Popconfirm title="确认删除?" onConfirm={() => handleDelete(record.key)} zIndex={2003}>
            <a>删除</a>
          </Popconfirm>
        ) : null,
    },
  ];

  // 获取业务类型项目
  const getTypName = async () => {
    try {
      const res = await postCPASToolsAipsData('localJsonData', {
        dataName: 'BAS_mainType',
        action: 'get'
      })
      const data = res?.data;
      if (data && data.length) {
        const temp = [];
        for(let i = 0; i<data.length; i++) {
          temp.push({
            key: i,
            name: data[i]
          });
        }
        setDataSource(temp);
      }
    } catch (error) {
      console.log(error);
    }
  };
  // useEffect(() => {
  //   getTypName();
  // }, [dbname]);
  const handleAdd = () => {
    if(!inputVal) {
      return notify('标准类型名称不能为空', 'error', 2000);
    }
    const newData: DataType = {
      key: count,
      name: inputVal,
    };
    const beforeData = dataSource.slice(0, dataSource.length-1);
    const emptyData = dataSource.slice(dataSource.length-1);
    setDataSource([...beforeData, newData, ...emptyData]);
    setInputVal("");
    setCount(count + 1);
  };

  const handleSave = (row: DataType) => {
    const newData = [...dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    setDataSource(newData);
  };

  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell,
    },
  };

  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: (record: DataType) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });
  const onInputChange = (e: any) => {
    const value = e?.target?.value;
    if(value) {
      setInputVal(value);
    }
  }
  const onOk = async () => {
    const result = [];
    for(let i = 0; i<dataSource.length; i++) {
      if(dataSource[i]?.name) {
        result.push(dataSource[i].name);
      }
    }
    try {
      const res = await postCPASToolsAipsData('localJsonData', {
        dataName: 'BAS_mainType',
        data: result,
        action: 'update'
      })
      if(okCallback) {
        okCallback(dataSource);
      }
    }catch(error) {
      console.log(error);
    }
    setConfirmOpen(false);
  }
  const onCancel = () => {
    if(cancelCallback) {
      cancelCallback();
    }
    setConfirmOpen(false);
  }
  return (
    <Modal
      title="设置标准业务类型"
      width={"40vw"}
      className="set-standard-modal"
      open={confirmOpen}
      onOk={onOk}
      onCancel={onCancel}
      okText="确认"
      cancelText="取消"
      zIndex={2000}
      style={{ top: 185, height: "60vh" }}
    >
      <Row style={{paddingBottom: 12}}>
        <Col span={18} style={{marginRight: 10}}>
          <Input onChange={onInputChange} value={inputVal} style={{height: 30, marginTop: 1, }}/>
        </Col>
        <Col>
          <Button onClick={handleAdd} type="primary">
            新增类型
          </Button>
        </Col>
      </Row>
      <Table<DataType>
        components={components}
        rowClassName={() => 'editable-row'}
        bordered
        dataSource={dataSource}
        scroll={{ y: 325 }}
        pagination={false}
        columns={columns as ColumnTypes}
      />
    </Modal>
  );
});

export default SetStandardType;
